package product

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"golang.org/x/time/rate"
	"mallgo/internal/common/response"
	"mallgo/internal/resources/product/model"
	"mallgo/internal/resources/product/resource"
	"net/http"
	"time"
)

// 商品增删改查控制器
type ProductController struct {
	productResource *resource.ProductResource
	limiter         *rate.Limiter
}

func NewProductController(productResource *resource.ProductResource) *ProductController {
	limiter := rate.NewLimiter(rate.Every(200*time.Millisecond), 5) //// 使用限流器作为中间件
	return &ProductController{productResource, limiter}
}

func (h *ProductController) create(c *gin.Context) {

	if h.limiter.Allow() == false {
		fmt.Println("====Disallow======", time.Now())
		c.JSON(http.StatusOK, response.Error(500, "请求过于频繁，请稍后再试"))
	} else {
		res := h.productResource.Create(c.Request.Context(), &model.Product{})
		c.JSON(http.StatusOK, res)
		fmt.Println("====Allow======", time.Now())

	}
}
